package edu.usm.roberge.orbitz;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.usm.roberge.HttpRequest;

/**
 * The initial request in the sequence to the Orbitz website
 * Gathers generated cookies and generated parameters from Orbitz 
 * site that are required to successfully submit the "find flight" form
 */
public class OrbitzIndexRequest {

	private static final String URL = "http://www.orbitz.com";
	private final HttpRequest request;
	
	// this regex grabs 2 things:
	// the unique URL to submit the form to
	// and the hidden input elements that are also required to submit form properly
	private final Pattern FORM_REG_EX = Pattern.compile("<form(?:.*?)id=\"airbotForm\"(?:.*?)action=\"([^\\\"]+)\"[^>]*>(.*?)</form>");
	
	// regex that will extract all hidden input elements (name and value)
	private final Pattern INPUT_ELEMENT_REG_EX = Pattern.compile("<input(?:.*?)name=\"([^\"]*)\"(?:.*?)value=\"([^\\\"]*)\"");
	
	public OrbitzIndexRequest() {
		request = new HttpRequest(URL);
	}
	
	public OrbitzData getOrbitzData() {
		OrbitzData data = new OrbitzData();
		
		String response = request.makeRequest();
		data.addCookies(request.getHeader("Set-Cookie"));
		
		processResponse(response, data);
		
		return data;
	}

	private void processResponse(String response, OrbitzData data) {
		Matcher matcher = FORM_REG_EX.matcher(response);
		if (!matcher.find()) {
			// TODO: record error
		}
		data.setSubmissionUrl(matcher.group(1));
		addHiddenParameters(matcher.group(2), data);
	}

	private void addHiddenParameters(String group, OrbitzData data) {
		Matcher matcher = INPUT_ELEMENT_REG_EX.matcher(group);
		while(matcher.find()) {
			data.addHiddenParameter(matcher.group(1), matcher.group(2));
		}
	}
}
